package some

import (
	"bytes"
	"fmt"

	"gitee.com/thubcc/p2pgit/classedpack"
	"gitee.com/thubcc/p2pgit/constant"
	"gitee.com/thubcc/p2pgit/format"
	"gitee.com/thubcc/p2pgit/types"
)

// NewPackCB pack call back
func NewPackCB(pps *types.SomePuter) func(*format.Header, []byte) error {

	return func(h *format.Header, b []byte) (cerr error) {
		pf := new(bytes.Buffer)
		pf.Reset()
		buf := h.ToByte()

		if h.Header32.Size != uint32(len(b)+len(buf)) {
			return fmt.Errorf("Size error:%d,%d,%d", len(b), len(buf), h.Header32.Size)
		}
		h.Header32.HCRC32 = h.Header32.CRC()
		h32 := h.Header32.ToHash256()
		_, cerr = pf.Write(h32[:])
		if cerr != nil {
			return
		}

		_, cerr = pf.Write(buf)
		if cerr != nil {
			return
		}
		_, cerr = pf.Write(b)
		pfb := pf.Bytes()
		var ps = *pps
		for k, p := range ps {
			cerr = p.Put(pfb)
			if cerr == constant.ErrorNeedSplit {
				var tobedel types.Puter
				*pps, tobedel, cerr = ps.Split(k)
				if cerr == nil {
					fmt.Println(tobedel.(*classedpack.File).Name(), "removed")
				}
			}
			if cerr != nil {
				return
			}
		}
		return
	}
}

// Geter2Puter Con
func Geter2Puter(gs types.SomeGeter) (ps types.SomePuter) {
	for _, v := range gs {
		if cpf, ok := v.(*classedpack.File); ok {
			var pf types.Puter = cpf
			ps = append(ps, pf)
		}
	}
	return
}
